//
//  GWItemViewController.m
//  GiftWanted
//
//  Created by lanou on 15/11/9.
//  Copyright © 2015年 陈文杰. All rights reserved.
//

#import "GWItemViewController.h"
#import "GWItemModel.h"
#import "SDCycleScrollView.h"
#import "MBProgressHUD.h"
#import "GWPurchaseViewController.h"


@interface GWItemViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) GWItemModel *itemModel;
@property (nonatomic, strong) UIButton *purchaseButton;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UILabel *descriptionLabel;

@end

@implementation GWItemViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.titleLabel.text = @"礼物";
    [self.leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:(UIControlStateNormal)];
    [self.leftButton addTarget:self action:@selector(handleReturnButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 70, SCREEN_WIDTH, SCREEN_HEIGHT-100)];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [_mainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    _mainTableView.rowHeight = SCREEN_HEIGHT-130;
//    _mainTableView.scrollsToTop = YES;
    [self.view addSubview:_mainTableView];
    
    _purchaseButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _purchaseButton.frame = CGRectMake(SCREEN_WIDTH/2-50, SCREEN_HEIGHT-25, 100, 20);
    _purchaseButton.backgroundColor = [UIColor colorWithRed:1.000 green:0.379 blue:0.396 alpha:1.000];
    _purchaseButton.layer.cornerRadius = 10;
    _purchaseButton.layer.masksToBounds = YES;
    _purchaseButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [_purchaseButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [_purchaseButton setTitle:@"立即前往" forState:(UIControlStateNormal)];
//    _purchaseButton.layer.borderWidth = 1.0f;
//    _purchaseButton.layer.borderColor = [UIColor yellowColor].CGColor;
    [self.view addSubview:_purchaseButton];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [button setBackgroundImage:[UIImage imageNamed:@"up"] forState:(UIControlStateNormal)];
    button.frame = CGRectMake(SCREEN_WIDTH-40, SCREEN_HEIGHT-25, 20, 20);
    [button addTarget:self action:@selector(handleUpButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button];
    
    [self requestData];
}

- (void)requestData {
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDAnimationFade;
    hud.labelText = @"连接中…";
    AFHTTPRequestOperation *opreation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[@"http://api.liwushuo.com/v2/items/" stringByAppendingFormat:@"%@", self.id_s]]]];
    [opreation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        _itemModel = [[GWItemModel alloc] init];
        [_itemModel setValuesForKeysWithDictionary:dict[@"data"]];
        [self.purchaseButton setTitle:_itemModel.button_title forState:(UIControlStateNormal)];
        [self.purchaseButton addTarget:self action:@selector(handlePurchaseButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
        [self addHeaderView];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"网络请求失败");
    }];
    [opreation start];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    
//    return @"图文介绍";
//}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    headerView.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:15];
    label.text = @"图文介绍";
    [headerView addSubview:label];
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-130)];
//    _webView.scrollView.scrollsToTop = NO;
     [_webView loadHTMLString:_itemModel.detail_html baseURL:[NSURL fileURLWithPath:[NSBundle mainBundle].bundlePath]];
    [cell.contentView addSubview:_webView];
    return cell;
}

- (void)addHeaderView {
    
    _mainTableView.tableHeaderView = ({
        
        CGFloat height = [self heightForString:_itemModel.description_s];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH+100+height)];
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
        for (NSString *str in _itemModel.image_urls) {
            
            [arr addObject:[NSURL URLWithString:str]];
        }
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH) imageURLsGroup:arr];
        [view addSubview:_cycleScrollView];
        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, SCREEN_WIDTH+10, SCREEN_WIDTH-20, 30)];
        _nameLabel.text = _itemModel.name;
        [view addSubview:_nameLabel];
        _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, SCREEN_WIDTH+50, SCREEN_WIDTH-20, 20)];
        _priceLabel.textColor = [UIColor redColor];
        _priceLabel.text = [@"￥" stringByAppendingFormat:@"%@", _itemModel.price];
        [view addSubview:_priceLabel];
        _descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, SCREEN_WIDTH+80, SCREEN_WIDTH-20, height)];
        _descriptionLabel.font = [UIFont systemFontOfSize:12];
        _descriptionLabel.numberOfLines = 0;
        _descriptionLabel.textColor = [UIColor grayColor];
        _descriptionLabel.text = _itemModel.description_s;
        [view addSubview:_descriptionLabel];
        UIView *spr = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH+90+height, SCREEN_WIDTH, 10)];
        spr.backgroundColor = [UIColor colorWithWhite:0.913 alpha:1.000];
        [view addSubview:spr];
        view;
    });
}

- (CGFloat)heightForString:(NSString *)str {
    
    CGRect bounds = [str boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-20, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:12] forKey:NSFontAttributeName] context:nil];
    return bounds.size.height;
}

- (void)handlePurchaseButtonAction {
    
    GWPurchaseViewController *purchaseVC = [[GWPurchaseViewController alloc] init];
    purchaseVC.purchase_url = _itemModel.purchase_url;
    [self.navigationController pushViewController:purchaseVC animated:YES];
}

- (void)handleUpButtonAction {
    [self.mainTableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)handleReturnButtonAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
